package com.news.cloud.web.model;

import com.news.cloud.jpa.domain.User;
import org.apache.commons.lang.StringUtils;
import org.springframework.context.annotation.Scope;
import org.springframework.context.annotation.ScopedProxyMode;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by hiephn on 2014/07/14.
 */
@Component
@Scope(value = "session", proxyMode = ScopedProxyMode.TARGET_CLASS)
public class UserSessionInfo extends NameDescResponse<User> {
    private List<Role> roles;
    private String fbAccessToken;
    private String ggAccessToken;

    public UserSessionInfo() {
    }

    public void resetData() {
        this.setName(StringUtils.EMPTY);
        this.setDesc(StringUtils.EMPTY);
        this.setId(-1);
    }

    @Override
    public void setData(User entity) {
        super.setData(entity);
        if (entity.getRoles() != null) {
            this.roles = new ArrayList<>(entity.getRoles().size());
            for (com.news.cloud.jpa.domain.Role roleEntity : entity.getRoles()) {
                Role role = Role.fromValue(roleEntity.getName());
                if (role != null) {
                    this.roles.add(role);
                }
            }
        }
    }

    public String getGgAccessToken() {
        return ggAccessToken;
    }

    public void setGgAccessToken(String ggAccessToken) {
        this.ggAccessToken = ggAccessToken;
    }

    public String getFbAccessToken() {
        return fbAccessToken;
    }

    public void setFbAccessToken(String fbAccessToken) {
        this.fbAccessToken = fbAccessToken;
    }

    public List<Role> getRoles() {
        return roles;
    }

    public void setRoles(List<Role> roles) {
        this.roles = roles;
    }

    public enum Role {
        ADMIN("admin"),
        MANAGER("manager"),
        STAFF("staff");

        private String value;

        public String getValue() {
            return value;
        }

        private Role(String value) {
            this.value = value;
        }

        public static Role fromValue(String value) {
            Role[] roles = Role.values();
            for (Role role : roles) {
                if (StringUtils.equalsIgnoreCase(role.value, value)) {
                    return role;
                }
            }
            return null;
        }
    }
}
